package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"short-video-hub/cache"
	"short-video-hub/model"
	"strconv"
	"time"
)

func List(c *gin.Context) {
	/*
		SELECT
		cars.name as Name,
		cars.num as Num,
		cars.type as Type,
		cars.price as Price,
		orders.cid as Cid,
		orders.order_time as OrderTime,
		orders.order_price as OrderPrice,
		orders.order_people as OrderPeople,
		FROM
		orders
		LEFT JOIN cars ON orders.cid=cars.id
	*/
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "3"))
	offset := (page - 1) * size
	redis_key := "car_order_list" + strconv.Itoa(page)

	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var car_order []model.CarOrder
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"cars.name as Name",
			"cars.num as Num",
			"cars.type as Type",
			"cars.price as Price",
			"orders.cid as Cid",
			"orders.order_time as OrderTime",
			"orders.order_price as OrderPrice",
			"orders.order_people as OrderPeople",
		).Joins("LEFT JOIN cars ON orders.cid=cars.id").
			Offset(offset).Limit(size).Find(&car_order).Debug()
		jsonData, _ := json.Marshal(car_order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car_order)
	}
	var total int64
	model.DB.Model(&model.Order{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  car_order,
		"total": total,
	})

}
func Detail(c *gin.Context) {
	/*\
	SELECT
	orders.cid as Cid,
	orders.order_people as OrderPeople,
	orders.order_time as OrderTime,
	orders.order_price as OrderPrice,
	cars.name as Name,
	cars.type as Type,
	cars.num as Num,
	cars.price as Price
	FROM
	orders
	LEFT JOIN cars ON orders.cid=cars.id
	WHERE orders.id=1
	*/
	id := c.Query("id")
	redis_key := "car_order_detail" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var car_order model.CarOrder
	if cacheData == "" {
		model.DB.Table("orders").Select(
			"cars.name as Name",
			"cars.num as Num",
			"cars.type as Type",
			"cars.price as Price",
			"orders.cid as Cid",
			"orders.order_time as OrderTime",
			"orders.order_price as OrderPrice",
			"orders.order_people as OrderPeople",
		).Joins("LEFT JOIN cars ON orders.cid=cars.id").
			Where("orders.id=?", id).Find(&car_order).Debug()
		jsonData, _ := json.Marshal(car_order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &car_order)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": car_order,
	})
}
